//
//  HomeMainVC.swift
//  MIFI
//
//  Created by 金嗓子卡卡 on 2019/4/10.
//  Copyright © 2019年 NJMifi. All rights reserved.
//

import UIKit
import CWLateralSlide

class StatusMainVC: RootVC {

    private var chargingValue = 1
    
    private lazy var statusLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 60))
        label.top = menuBtn.bottom
        label.text = "Device disconnected"
        label.backgroundColor = clearColor
        label.textAlignment = .center
        label.textColor = whiteColor
        label.font = UIFont.systemFont(ofSize: 24)
        return label
    }()
    
    private lazy var menuBtn : UIButton = {
        let btn = UIButton(frame: CGRect(x: 16, y:phoneTop + 30, width: realValue_W(value: 60), height: realValue_W(value: 50)))
        btn.backgroundColor = clearColor
        btn.setBackgroundImage(UIImage(named: "left_menu"), for: .normal)
        btn.addTarget(self, action: #selector(menuAction), for: .touchUpInside)
        return btn
    }()
    
    private lazy var statusView: StatusView = {
        let viewBottom = (screenHeight - tabbarHeight) / 2 + 40
        let viewHeight = viewBottom - statusLabel.bottom
        let view = StatusView(frame: CGRect(x: 0, y: 0, width: viewHeight, height: viewHeight))
        view.centerX = screenWidth / 2
        view.bottom = viewBottom
        return view
    }()
    
    private lazy var netNameLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 0, y: statusView.bottom + 2, width: screenWidth, height: 40))
        label.textAlignment = .center
        label.textColor = whiteColor
        label.backgroundColor = clearColor
        label.font = statusLabel.font
        return label
    }()
    
  
    
    private lazy var batteryImageV: UIImageView = {
        let viewHeight = (screenHeight - statusView.bottom - tabbarHeight) / 5
        let imageV = UIImageView(frame: CGRect(x: 0, y: netNameLabel.bottom + 12, width: viewHeight, height: viewHeight))
        imageV.centerX = view.width / 2
        imageV.backgroundColor = clearColor
        imageV.image = UIImage(named: "battery_0")
        return imageV
    }()
    
    private lazy var downSpeedLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: batteryImageV.right + menuBtn.left, y: batteryImageV.top, width: upSpeedLabel.width, height: upSpeedLabel.height))
        label.textAlignment = .left
        label.backgroundColor = clearColor
        label.textColor = whiteColor
        label.attributedText = insertImageToString(image: UIImage(named: "down")!, frame: CGRect(x: 0, y: 0, width: 15, height: 20), index: 0, string: "0.00kb/s")
        label.font = UIFont.systemFont(ofSize: 18)
        return label
    }()
    
    private lazy var upSpeedLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 0, y: batteryImageV.top, width: batteryImageV.left - menuBtn.left * 2, height: batteryImageV.height))
        label.right = batteryImageV.left - menuBtn.left
        label.backgroundColor = clearColor
        label.textAlignment = .right
        label.textColor = whiteColor
        label.attributedText = insertImageToString(image: UIImage(named: "up")!, frame: CGRect(x: 0, y: 0, width: 15, height: 20), index: 0, string: "0.00kb/s")
        label.font = UIFont.systemFont(ofSize: 18)
        return label
    }()
    
    private lazy var memoryAlertLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 0, y: upSpeedLabel.bottom + 2, width: screenWidth, height: 40))
        label.textAlignment = .center
        label.textColor = whiteColor
        label.backgroundColor = clearColor
        label.font = statusLabel.font
        return label
    }()
    
    private lazy var connectBtn: UIButton = {
        let viewHeight = (screenHeight - statusView.bottom - tabbarHeight) / 4
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: viewHeight, height: viewHeight))
        btn.backgroundColor = clearColor
        btn.setImage(UIImage(named: "unconnect")!, for: .normal)
//        btn.tintColor = colorStr(color: "#2894FF")
        btn.centerX = view.width / 2
        btn.centerY = (screenHeight - tabbarHeight - batteryImageV.bottom) / 2 - 10 + batteryImageV.bottom
        btn.addTarget(self, action: #selector(connectAction), for: .touchUpInside)
        return btn
    }()
    
    private lazy var chargeAnimationView: UIImageView = {
        let imageV = UIImageView(frame: batteryImageV.frame)
        imageV.width = batteryImageV.width - 1
        imageV.height = batteryImageV.height - 1
        imageV.center = batteryImageV.center
        imageV.backgroundColor = clearColor
        imageV.image = UIImage(named: "charge_animation")
        imageV.isHidden = true
        return imageV
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        net_connect()
        getData()
    }
    
    @objc private func getData() {
        
        
        net_getDeviceInfo {[weak self] (model) in
         
            self!.statusView.refreshData(data: model)
            self!.refreshUI(model: model)
            
            if model == nil {
            
                 NotificationCenter.default.post(name: NSNotification.Name(rawValue: "deviceDisconnect"), object: nil)
             
                
            }else{
                
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "getDataRefreshSMS"), object: model)
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "changeBag"), object: model?.sms_unread_num)
            }
            
          
          
        }
    }
    
    override func configView() {
        view.addSubview(menuBtn)
        view.addSubview(statusLabel)
        view.addSubview(statusView)
        view.addSubview(netNameLabel)
        view.addSubview(batteryImageV)
        view.addSubview(downSpeedLabel)
        view.addSubview(upSpeedLabel)
        view.addSubview(memoryAlertLabel)
//        view.addSubview(connectBtn)
        view.addSubview(chargeAnimationView)
    }

    @objc private func menuAction() {
        
        if !self.isWIFIEnable() {
            
            let alertVC = UIAlertController(title: "Alert", message: "Open the WiFi settings", preferredStyle: .alert)
            let action = UIAlertAction(title: "I know", style: .cancel) { (action) in
                
            }
            alertVC.addAction(action)
            present(alertVC, animated: true, completion: nil)
            
            return
        }
        
        let newVC = StatusMenuVC()
        newVC.scanHandle = ({[weak self] in
            let scanVC = ScanQRCodeVC()
            scanVC.scanSuccess = ({ name, password in
                self!.showScanResult(name:name,password:password)
            })
            self!.cw_push(scanVC)
            
        })
        cw_showDefaultDrawerViewController(newVC)
    }
    
    private func showScanResult(name:String,password:String) {
        
        if #available(iOS 11.0, *) {
            //系统版本高于11.0
            
            self.connectWifiSSID(name, andPassword: password) { (error) in
                
                var alertNote = "Successful connection"
                
                if (error != nil) {
                    
                    alertNote = error?.localizedDescription ?? ""
                    
                }
                
                let alertVC = UIAlertController(title: "Alert", message: alertNote, preferredStyle: .alert)
                let action = UIAlertAction(title: "I know", style: .cancel) { (action) in
                    self.navigationController?.popViewController(animated: true)
                }
                alertVC.addAction(action)
                self.present(alertVC, animated: true, completion: nil)
                
            }
            
            
            
            
        } else {
            //系统版本低于11.0
            
            UIPasteboard.general.string = password
            let message = "WiFi Name:\(name)\n" + "Password:\(password)\n" + "The password has been copied to the clipboard,please go to\"set\"->\"woreless LAN\"password paste"
            let alertVC = UIAlertController(title: "Alert", message: message, preferredStyle: .alert)
            let action = UIAlertAction(title: "I know", style: .cancel) { (action) in
                
            }
            alertVC.addAction(action)
            present(alertVC, animated: true, completion: nil)
        }
        
        
    }
    
    @objc private func connectAction() {
    
    }
    
    private func startCharge() {
        chargeAnimationView.isHidden = false
        guard chargeAnimationView.layer.animation(forKey: "rotation") == nil else {
            return
        }
        let animation = CABasicAnimation(keyPath: "transform.rotation")
        animation.duration = 4
        animation.fromValue = 0
        animation.toValue = 2 * Double.pi
        animation.isRemovedOnCompletion = false
        animation.repeatCount = MAXFLOAT
        chargeAnimationView.layer.add(animation, forKey: "rotation")
    }
    
    private func stopCharge() {
        chargeAnimationView.isHidden = true
        chargeAnimationView.layer.removeAllAnimations()
    }
    
    private func refreshUI(model:StatusVCDeviceInfoModel?) {
        guard model != nil else {
            refreshNodata()
            return
        }
        
        if UserInfoManager.shared().isLogin && statusView.remianMemory <= 0 {
            memoryAlertLabel.text = "Your data limit has reached!"
            if !UserInfoManager.shared().data_volume_limit_switch {
               memoryAlertLabel.text = ""
            }
        }else{
            memoryAlertLabel.text = ""
        }
       
        UserInfoManager.shared().isConnected = true
        netNameLabel.text = model!.network_provider!
        if !isEmpty(string: model?.SSID1) {
            statusLabel.text = model!.SSID1
        }else {
            if model!.ppp_status!.caseInsensitiveCompare("ppp_connected") == .orderedSame {
                var status = model!.SSID1
                if status?.first == "/" && status?.last == "/" {
                    status = String(status![1..<status!.count - 1])
                }
                statusLabel.text = model!.SSID1
                
                if model!.SSID1!.isEmpty  {
                    
                    statusLabel.text = "Device disconnected"
                    statusView.changeBackToGreen()
                }
                
            }else{
                
                 statusLabel.text = "Device disconnected"
                statusView.changeBackToGreen()
                
            }
        }

        let downS = Double(model!.realtime_rx_thrpt!) == nil ? 0.00 : Double(model!.realtime_rx_thrpt!)!
        let upS = Double(model!.realtime_tx_thrpt!) == nil ? 0.00 : Double(model!.realtime_tx_thrpt!)!
        downSpeedLabel.attributedText = insertImageToString(image: UIImage(named: "down")!, frame: CGRect(x: 0, y: 0, width: 15, height: 20), index: 0, string: String(format: "%.2fkb/s", downS / 1024))
        upSpeedLabel.attributedText = insertImageToString(image: UIImage(named: "up")!, frame: CGRect(x: 0, y: 0, width: 15, height: 20), index: 0, string: String(format: "%.2fkb/s", upS / 1024))
        if model!.battery_charging == "1" {
            startCharge()
            chargingValue = chargingValue == 4 ? 1 : chargingValue + 1
            batteryImageV.image = UIImage(named: "battery_\(chargingValue)")
        }else {
            stopCharge()
            batteryImageV.image = UIImage(named: "battery_\(model!.battery_pers!)")
        }
        
    }
    
    private func refreshNodata() {
        stopCharge()
        batteryImageV.image = UIImage(named: "battery_0")
        downSpeedLabel.attributedText = insertImageToString(image: UIImage(named: "down")!, frame: CGRect(x: 0, y: 0, width: 15, height: 20), index: 0, string: String(format: "%.2fkb/s", 0 / 1024))
        upSpeedLabel.attributedText = insertImageToString(image: UIImage(named: "up")!, frame: CGRect(x: 0, y: 0, width: 15, height: 20), index: 0, string: String(format: "%.2fkb/s", 0 / 1024))
        netNameLabel.text = ""
        UserInfoManager.shared().isConnected = false
        netNameLabel.text = ""
        statusLabel.text = "Device disconnected"
        memoryAlertLabel.text = ""
    }
}

